import { t } from 'i18next'
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'
import { Modal, Select, Button, Input, InnerInputRef, Message, TriggerInstance } from '@kedacom/react-next'
import { StyledWrap, StyledVmpSelectItem, StyledVmpPlanModal, StylePreview } from './style'
import { getCheckPreNameRule } from '@/utils'
import { defaultPlan, PlanEntity, PlanRef, RevertPlanEntity } from './interface'
import { useCreateContentStore } from '../../../store'
import {
	fetchDeleteVmpPlan,
	fetchEditVmpPlan,
	fetchGetVmpPlan,
	fetchGetVmpPlanList,
	fetchSaveVmpPlan,
} from '@/api/create/vmp'
import { useMeetingVmpStore } from '../store'
import shallow from 'zustand/shallow'
import Alert, { confirmModal } from '@/components/Alert'
import { allVmpStyleData } from '../VmpView/interface'
import { useMeetingParamsStore } from '../../meetingParams/store'
import { useGlobalStore } from '@/store/global'
import { initPollData } from '../store.combine'

export interface VmpPlanProps {
	disabled?: boolean
	getVmpParam: () => any | null
}

const VmpPlan = forwardRef((props: VmpPlanProps, ref: React.Ref<PlanRef>) => {
	/**画面合成预案*/
	// const [planOptions, setPlanOptions] = useState<RevertPlanEntity[]>([
	// 	{ label: t('默认预案'), value: '0', mode: undefined, layout: undefined },
	// ])
	const setName = (v: string) => {
		update({ vmpPlanName: v })
	}
	const setPlanValue = (v: string) => {
		update({ vmpPlanValue: v })
	}
	const setPlanOptions = (arr: RevertPlanEntity[]) => {
		update({ planOptions: arr })
	}
	/**预案名称 */
	// const [name, setName] = useState('')
	/**预案名称弹窗 */
	const [isSavePlanOpen, setIsSavePlanOpen] = useState(false)
	/**保存预案的时候用来校验正则*/
	const inputRef = useRef<InnerInputRef>(null)
	const selectRef = useRef<TriggerInstance>(null)
	/**预案id*/
	// const [planValue, setPlanValue] = useState('0')
	const { _name, update, vmpPlanName, vmpPlanValue, planOptions, needUpdate } = useMeetingVmpStore(
		(state) => ({
			planOptions: state.planOptions,
			_name: state.name,
			vmpPlanName: state.vmpPlanName,
			vmpPlanValue: state.vmpPlanValue,
			update: state.update,
			needUpdate: state.needUpdate,
		}),
		shallow
	)
	const { disabled, getVmpParam } = props

	const SWITCH = useGlobalStore((state) => state.SWITCH)
	const _container = useCreateContentStore((state) => state._container, shallow)

	useImperativeHandle(ref, () => ({
		getValue() {
			return planOptions.find((item) => item.value === vmpPlanValue) ?? null
		},
	}))
	useEffect(() => {
		getVmpPlanList()
	}, [])
	useEffect(() => {
		let _item = planOptions.find((item) => item.label === _name)
		setPlanValue(_item?.value ?? '0')
	}, [_name, planOptions])
	/**获取合成预案列表*/
	const getVmpPlanList = async () => {
		const { preKey, isTemplate } = useCreateContentStore.getState()
		const vmpPlanData = await fetchGetVmpPlanList(preKey, isTemplate)
		if (vmpPlanData && vmpPlanData.success) {
			let arr: RevertPlanEntity[] = revert_plan_get_paln_option(vmpPlanData.data)
			setPlanOptions(arr)
		}
	}
	/**转换预案数据(处理成为预案下拉列表)*/
	const revert_plan_get_paln_option = (plan_source?: Array<PlanEntity>): Array<RevertPlanEntity> => {
		let arr: RevertPlanEntity[] = []
		if (plan_source) {
			arr = plan_source.map((item) => {
				return {
					label: item.name,
					value: item.id,
					mode: item.mode,
					layout: item.layout,
				}
			})
		}
		arr.unshift(defaultPlan)
		return arr
	}
	const reset = () => {
		const meetingType = useMeetingParamsStore.getState().meetingType
		if (meetingType === 0 || meetingType === 1) {
			update({
				mt_name_style: {
					font_color: '#FFFFFF',
					font_size: 1,
					position: 1,
				},
				poll: null,
				broadcast: 1,
				except_self: 0,
				id: '',
				layout: 0,
				members: [],
				mode: 2,
				// enable: false,
				show_mt_name: 1,
				name: '',
				voice_hint: 1,
			})
		} else {
			update({
				mt_name_style: {
					font_color: '#FFFFFF',
					font_size: 1,
					position: 1,
				},
				poll: null,
				broadcast: 1,
				except_self: 0,
				id: '',
				layout: 34,
				members: [],
				mode: 1,
				// enable: false,
				show_mt_name: 0,
				name: '',
				voice_hint: 1,
			})
		}
	}
	//载入预案
	const changePlan = async (id: string) => {
		if (id === '0') {
			reset()
			return
		}
		const { preKey, isTemplate } = useCreateContentStore.getState()
		fetchGetVmpPlan(preKey, isTemplate, id).then((res) => {
			if (res.success) {
				const meetingType = useMeetingParamsStore.getState().meetingType
				if (meetingType === 2) {
					// let sfuStyleArr = [1, 2, 4, 5, 34, 64, 13, 7, 8, 18, 65, 66, 19, 17, 67, 11]
					if (res.mode !== 1) {
						Alert(t('超元RTC会议暂不支持该预案'))
						return
					}
				}
				setPlanValue(id)
				update({
					mt_name_style: {
						font_color: res.mt_name_style?.font_color ?? '#FFFFFF',
						font_size: res.mt_name_style?.font_size ?? 1,
						position: res.mt_name_style?.position ?? 1,
					},
					show_mt_name: res.show_mt_name ?? 1,
					broadcast: res.broadcast,
					voice_hint: res.voice_hint,
					layout: res.mode === 2 ? 0 : res.layout,
					name: res.name ?? '',
					members: res.members ?? [],
					except_self: res.except_self ?? 1,
					mode: res.mode,
					poll: res.mode === 4 || res.mode === 3 ? res.poll : null,
					needUpdate: !needUpdate,
				})
				initPollData(res.poll ?? null)
			}
		})
	}
	//删除预案
	const deletePlan = (e: React.MouseEvent, item: RevertPlanEntity) => {
		e.stopPropagation()
		let isCur = item.value === vmpPlanValue ? true : false
		const { preKey, isTemplate } = useCreateContentStore.getState()
		confirmModal({
			msg: <div>{t('是否确定删除{{name}}？', { name: item.label })}</div>,
			onOk: async () => {
				fetchDeleteVmpPlan(preKey, isTemplate, item.value).then((res) => {
					if (res.success) {
						let arr = planOptions.filter((i) => i.value !== item.value)
						setPlanOptions(arr)
						if (isCur) {
							setPlanValue('0')
							reset()
						}
					} else {
						Alert(res.description ?? '')
					}
				})
			},
		})
	}
	//保存预案
	const savePlanClick = () => {
		if (vmpPlanValue === '0') {
			setIsSavePlanOpen(true)
			setName('')
		} else {
			let param = getVmpParam()
			if (!param) return
			const { preKey, isTemplate } = useCreateContentStore.getState()
			fetchEditVmpPlan(preKey, isTemplate, vmpPlanValue, param).then((res) => {
				if (res.success) {
					Message.info(t('预案已保存'))
					getVmpPlanList()
				}
			})
		}
	}
	/**另存为*/
	const saveAsPlan = () => {
		setIsSavePlanOpen(true)
		setName(_name + '1')
	}
	/**新增*/
	const savePlan = async () => {
		let valid = await inputRef.current?.valid()
		if (!valid) return
		let param = getVmpParam()
		if (!param) return
		let newParam = { ...param, name: vmpPlanName, id: '' }
		const { preKey, isTemplate } = useCreateContentStore.getState()
		fetchSaveVmpPlan(preKey, isTemplate, newParam).then((res) => {
			if (res.success) {
				Message.info(t('预案保存成功'))
				update({ name: vmpPlanName })
				setIsSavePlanOpen(false)
				getVmpPlanList()
			} else {
				Alert(res.description)
			}
		})
	}
	/**依据选项数据确定className */
	const getClassName = (item: RevertPlanEntity) => {
		if (item.value == '0') {
			return 'default'
		} else if (item.mode === 2) {
			return 'auto'
		} else {
			const _item = allVmpStyleData.find((_vmpStyleItem) => {
				return _vmpStyleItem.id === item.layout
			})
			return _item?.className
		}
	}

	return (
		<StyledWrap className="mcc-vmp-plan-wrap">
			<div className="mcc_vmp_plan_option">
				<Select
					container={() => _container}
					ref={selectRef}
					width={366}
					panelLineHeight={40}
					options={planOptions}
					value={vmpPlanValue}
					disabled={disabled}
					optionRender={(option, selected) => {
						return (
							<StyledVmpSelectItem
								className={selected ? 'selected' : ''}
								onClick={(e) => {
									e.stopPropagation()
									selectRef.current?.close()
									changePlan(option.value)
								}}
							>
								<span className="select-icon"></span>
								{getClassName(option as any) === 'auto' ? (
									<div className="auto">
										<span>{t('自动')}</span>
									</div>
								) : (
									<StylePreview className={`preview ${getClassName(option as any)}`}></StylePreview>
								)}
								<span className="name">{option.label}</span>
								{option.value !== '0' && (
									<span className="delete-icon" onClick={(e) => deletePlan(e, option as any)}></span>
								)}
							</StyledVmpSelectItem>
						)
					}}
				/>
				{vmpPlanValue === '0' && (
					<Button className="savePlan" onClick={savePlanClick}>
						{t('保存')}
					</Button>
				)}
				{vmpPlanValue !== '0' && (
					<>
						<Button className="updatePlan" onClick={savePlanClick}>
							{t('保存')}
						</Button>
						<Button className="saveAsPlan" onClick={saveAsPlan}>
							{t('另存为')}
						</Button>
					</>
				)}
			</div>
			<Modal
				open={isSavePlanOpen}
				title={t('保存预案')}
				width={400}
				height={300}
				okText={t('保存')}
				onOk={savePlan}
				onCancel={() => {
					setIsSavePlanOpen(false)
					setName('')
				}}
				cancelText={t('取消')}
			>
				<StyledVmpPlanModal>
					<div className="label">{t('预案名称')}</div>
					<Input
						width={250}
						placeholder={t('请输入预案名称')}
						focusMsg={t('预案名称最多可输入16个字符')}
						innerRef={inputRef}
						maxLength={16}
						rule={{
							required: {
								showIcon: false,
								msg: t('预案名称不能为空'),
							},
							regular: getCheckPreNameRule(SWITCH.characterLimit),
						}}
						value={vmpPlanName}
						onChange={(e, v) => setName(v)}
					/>
				</StyledVmpPlanModal>
			</Modal>
		</StyledWrap>
	)
})
export default VmpPlan
